import { Spin } from 'antd'
import { useOwner, getSender } from '@/desktop/logics/chat/info'
import { Record } from '@/desktop/views/chat/record'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { fetchOnlineRecords } from '@/services/contact-chat'
import type { ChatRecord } from '@/services/contact-chat'
import { makeContactIdByConversationId } from '@/services/contacts'
import { type Focusing } from './logics'
import './related-records.module.less'

export function RelatedRecords(props: { focusing: Focusing }) {
  const { focusing } = props
  const { wxid, conversationId } = focusing.match

  const [account] = useStreams(services.auth.account$)

  const rawContact = useMemo(() => {
    const contactId = makeContactIdByConversationId(wxid, conversationId)
    return services.contacts.getById(contactId ?? '')
  }, [wxid, conversationId])
  const contact = rawContact ?? { ownerWxid: wxid }

  const owner = useOwner(contact)

  const customGetSender = rawContact
    ? (record: ChatRecord) => getSender({ record, contact: rawContact, owner })
    : () => ({ name: focusing.match.conversationId, avatar: '' })

  const [records, setRecords] = useState<ChatRecord[] | null>(null) // null 代表加载中
  const focusingElementRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    let cancelled = false
    async function load() {
      const commonParams = {
        wxid: focusing.match.wxid,
        conversationId: focusing.match.conversationId,
        lastTimestamp: focusing.record.timestamp,
        pageSize: 100,
      }
      const prevPromise = fetchOnlineRecords({ ...commonParams, previous: true })
      const nextPromise = fetchOnlineRecords({ ...commonParams, previous: false })
      const [prevRes, nextRes] = await Promise.all([prevPromise, nextPromise])
      if (cancelled) return
      setRecords([
        ...(prevRes.success ? prevRes.data.records : []),
        focusing.record,
        ...(nextRes.success ? nextRes.data.records : []),
      ])

      // 将目标记录滚动到视图中心
      requestAnimationFrame(() => {
        const element = focusingElementRef.current
        if (element) element.scrollIntoView({ block: 'center' })
      })
    }
    void load()
    return () => {
      cancelled = true
    }
  }, [focusing])

  if (!records) return <Spin styleName="loading" tip="聊天记录加载中..." />

  return <div styleName="related-records">
    {records.map(record => {
      const renderedRecord = <Record
        key={`${record.id}-${record.timestamp}`}
        sender={customGetSender(record)}
        contact={contact}
        account={account ?? undefined}
        record={record}
        readonly={true}
      />
      return focusing.record === record ? (
        <div styleName="focusing" ref={focusingElementRef}>
          {renderedRecord}
        </div>
      ) : (
        renderedRecord
      )
    })}
  </div>
}
